<template>
	<div class="uiue-card">
		<div class="tit" v-if="isblack === '1'">移动端{{ mdname }}</div>
		<div class="tit" v-else>{{ title }}{{ mdname }}</div>
		<a-button type="primary" style="margin: 10px 0" @click="exportList" :loading="uploading">下载</a-button>
		<a-table :dataSource="data.dataSource" :columns="columns" :loading="loading" :pagination="false" size="middle"
			bordered>
			<template v-slot:bodyCell="{ column, record }">
				<!-- <template v-if="column.dataIndex === 'operation' && (showGray || isYuny)">
					<a-popconfirm v-if="data.dataSource.length" title="确定删除?" @confirm="onDelete(record.grayscaleId)">
						<a>删除</a>
					</a-popconfirm>
				</template>
<template v-if="column.dataIndex === 'operation' && isblack !== '0' && isdb == '0'">
					<a-popconfirm v-if="data.dataSource.length" title="确定删除?" @confirm="onDelete(record.grayscaleId)">
						<a>删除</a>	
					</a-popconfirm>
				</template> -->
				<template v-if="column.dataIndex === 'operation'">
					<a-popconfirm v-if="data.dataSource.length" title="确定删除?" @confirm="onDelete(record.grayscaleId)">
						<a>删除</a>
					</a-popconfirm>
				</template>
			</template>
		</a-table>
		<!-- isblack 0灰名单   1黑名单   2白名单 -->
		<div class="box-pagin">
			<a-pagination show-size-changer show-quick-jumper :show-total="(total) => `共 ${total} 条`"
				v-model:current="searchFormState.current" v-model:pageSize="searchFormState.size" :total="total"
				@change="pageNumberChange" />
		</div>
		<a-button class="btns" type="dashed" v-if="showGray" block @click="add">
			<template #icon><plus-outlined /></template>
			添加名单
		</a-button>
		<!-- <a-button class="btns" type="dashed" v-if="isblack === '1' || isblack === '2'" block @click="add">
			<template #icon><plus-outlined /></template>
			添加名单
		</a-button> -->
	</div>
	<a-modal v-model:visible="showModal" width="70vw" :title="`确认发布${mdname}`" @ok="handleOk" @cancel="handcancel">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState1" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="账号搜索" name="grayscaleAccounts">
						<a-input v-model:value="searchFormState1.grayscaleAccounts" placeholder="请输入账号" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="loadData(1)">查询</a-button>
					<a-button style="margin: 0 8px" @click="() => searchFormRef.resetFields()">重置</a-button>
				</a-col>
			</a-row>
		</a-form>
		<a-divider style="margin-top: 0" />
		<a-space style="margin-bottom: 18px">
			<a-button type="primary" :loading="uploading" @click="exportList"> 下载名单 </a-button>

			<a-upload :accept="fileType" :customRequest="importRoster" :showUploadList="false">
				<a-button :loading="uploading">导入名单</a-button>
			</a-upload>
			<a-button :loading="uploading" @click="downloadTemplate">下载模板</a-button>
		</a-space>

		<a-table :dataSource="data.dataSourceFz" :columns="columns" size="middle" :loading="loading" :pagination="false"
			class="box-table">
			<!-- <a-popconfirm v-if="data.dataSource.length > 0" title="确定删除?" @confirm="onDelete(record.key)">
				<a>删除</a>
			</a-popconfirm> -->
			<template v-slot:bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'operation'">
					<a-popconfirm title="确定删除?" @confirm="onDelete1(record.grayscaleId)">
						<a>删除</a>
					</a-popconfirm>
				</template>
			</template>
		</a-table>
		<div class="box-pagin">
			<a-pagination show-size-changer show-quick-jumper :show-total="(total) => `共 ${total} 条`"
				v-model:current="searchFormState1.current" v-model:pageSize="searchFormState1.size" :total="total"
				@change="pageNumberChange1" />
		</div>
	</a-modal>
</template>

<script setup name="GrayscaleTable">
import grayscaleApi from '@/api/biz/grayscaleApi'
import tool from '@/utils/tool'
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import store from '@/store'
const route = useRoute()
const datas = inject('detailDate')
const fileType = '.xlsx,.xls'
const uploading = ref(false)
const loading = ref(false)
const props = defineProps({
	configKey: {
		type: String
	},
	isblack: {
		type: String
	}
})
const formTypeId = route.query.formType
const isBack = computed(() => {
	return route.query.stepId === 'a001' ? true : false
})
const approvalType = route.query.approvalType

// const isdb = ref(tool.session.get('doneStatus'))

const config = [
	{ txt: 'pc', key: '1', subTable: 'pcPropertiesList' },
	{ txt: 'html5', key: '2', subTable: 'appPropertiesList' },
	{ txt: 'android', key: '3', subTable: 'androidPropertiesList' },
	{ txt: 'ios', key: '4', subTable: 'iosPropertiesList' },
	{ txt: 'umap', key: '5', subTable: 'umapPropertiesList' },
	{ txt: 'html5', key: '6', subTable: 'appPropertiesList' },
]
// grayscaleType 名单类型 1黑名单 0灰名单 2白名单
// appId 应用id
// propertyType 属性类型  pc，app，ios，android, umap

// 监听用户输入的版本号，去请求新的名单
watch(() => store.state.appinfo.appVersion, () => {
	loadData()
})



const params = computed(() => {
	const obj = formTypeId ? datas.value?.appInfoAppPropertiesAddParam : datas.value?.appPropertiesList[0]
	return {
		grayscaleType: props.isblack,
		// 如有子表id就传，没有传‘’
		appId: obj?.id || '',
		// 中间表id
		propertyId: datas.value.id,
		appCode: datas.value.appCode,
		appVersion: store.state.appinfo.appVersion || '',
		propertyType: config.find((v) => v.key === props.configKey).txt,
		upgrade: tool.session.get('approvalType') === '3' ? '1' : '' // 如果是升级传1
	}
})
// 列表搜索条件
let searchFormState = reactive({
	current: 1,
	size: 10,
	grayscaleAccounts: ''
})
let searchFormState1 = reactive({
	current: 1,
	size: 10,
	grayscaleAccounts: ''
})
let total = ref(0)
const title = computed(() => {
	return props.configKey === '1' ? '门户端' : '移动端'
})
const mdname = computed(() => {
	let str = ''
	switch (props.isblack) {
		case '0':
			str = '灰度名单'
			break
		case '1':
			str = '黑名单'
			break
		case '2':
			str = '白名单'
			break
		default:
			break
	}
	return str
})
onMounted(() => {
	loadData()
})
const currentName = inject('currentName')
// 控制add按钮
const showGray = computed(() => {
	let bool = false
	const arr = ['生产环境灰度测试/材料提交', '申请人提交生产材料']
	let doneStatus = tool.session.get('doneStatus')
	if (arr.includes(currentName?.value) && doneStatus && doneStatus === '0') {
		bool = true
	}
	// 变更
	if (formTypeId) bool = true

	if ((approvalType === '2' || approvalType === '3') && isBack.value) {
		bool = true
	}
	return bool
})

// 控制灰度名单删除
const isYuny = computed(() => {
	let bool = false
	let doneStatus = tool.session.get('doneStatus')
	if (currentName?.value === '运营组审核' && props.isblack === '0' && doneStatus && doneStatus === '0') {
		bool = true
	}
	return bool
})

// const cappId = computed(() => {
// 	let str = '2'
// 	console.log(props.isblack)
// 	if (currentName?.value === '提交上线材料' && !props.isblack) {
// 		str = '1'
// 	}
// 	return str
// })

const pageNumberChange = (page, pageSize) => {
	searchFormState.current = page
	searchFormState.size = pageSize
	loadData()
}
const pageNumberChange1 = (page, pageSize) => {
	searchFormState1.current = page
	searchFormState1.size = pageSize
	loadData(1)
}
const handcancel = () => {
	loadData()
}
const loadData = (search) => {
	// const cappId = tool.data.get('currentName') === '提交上线材料' ? '1' : '2'
	let obj = { ...searchFormState, ...params.value, cappId: '2' }
	if (search == 1) {
		obj = { ...obj, ...searchFormState1 }
	}
	loading.value = true
	grayscaleApi.getPage(obj).then((res) => {
		const { records, total: num } = res
		if (search != 1) {
			data.dataSource = records
		}
		data.dataSourceFz = records
		total.value = num
		loading.value = false
	})
}
const data = reactive({
	dataSource: [],
	dataSourceFz: []
})
// const columns = ref([
// 	{
// 		title: '用户',
// 		dataIndex: 'grayscaleName',
// 		key: 'grayscaleName'
// 	},
// 	{
// 		title: '账号',
// 		dataIndex: 'grayscaleAccounts',
// 		key: 'grayscaleAccounts'
// 	},
// 	{
// 		title: '操作',
// 		dataIndex: 'operation'
// 	}
// ])
const columns = computed(() => {
	let colm = [{
		title: '用户',
		dataIndex: 'grayscaleName',
		key: 'grayscaleName'
	},
	{
		title: '账号',
		dataIndex: 'grayscaleAccounts',
		key: 'grayscaleAccounts'
	}]
	let obj = {
		title: '操作',
		dataIndex: 'operation'
	}
	let doneStatus = tool.session.get('doneStatus')
	if (doneStatus && doneStatus === '0') {
		if (currentName?.value === '申请人提交生产材料' || currentName?.value === '生产环境灰度测试/材料提交') {
			colm.push(obj)
		}
		// if (props.isblack === '1' || props.isblack === '2') {
		// 	colm.push(obj)
		// }
	}
	// 变更
	if (formTypeId) colm.push(obj)

	return colm
})



const onDelete = (grayscaleId) => {
	const arr = [{ grayscaleId }]
	grayscaleApi.remove(arr).then((res) => {
		searchFormState.current = 1
		searchFormState.size = 10
		loadData()
	})

}
const onDelete1 = (grayscaleId) => {
	const arr = [{ grayscaleId }]
	grayscaleApi.remove(arr).then((res) => {
		searchFormState1.current = 1
		searchFormState1.size = 10

		loadData(1)
	})
}
const showModal = ref(false)
const add = () => {
	showModal.value = true
}
const handleOk = () => {
	showModal.value = false
	loadData()
}

const searchFormRef = ref()
// 下载模板
const downloadTemplate = () => {
	uploading.value = true
	grayscaleApi
		.getTemplate()
		.then((res) => {
			const blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' })
			const contentDisposition = res.headers['content-disposition']
			const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
			const $link = document.createElement('a')
			$link.href = URL.createObjectURL(blob)
			$link.download = decodeURIComponent(patt.exec(contentDisposition)[1])
			$link.click()
			document.body.appendChild($link)
			document.body.removeChild($link) // 下载完成移除元素
			window.URL.revokeObjectURL($link.href) // 释放掉blob对象
			uploading.value = false
		})
		.catch(() => {
			uploading.value = false
		})
}
// 导入名单
const importRoster = async (file) => {
	const form = new FormData()
	form.append('file', file.file)
	form.append('grayscaleType', params.value.grayscaleType)
	form.append('appId', params.value.appId)
	form.append('propertyType', params.value.propertyType)
	form.append('propertyId', params.value.propertyId)
	form.append('appCode', params.value.appCode)
	form.append('appVersion', params.value.appVersion)
	form.append('upgrade', params.value.upgrade)
	if (datas.value.appAccess.includes(',') && datas.value.appAccess.includes('1')) {
		// 服务端要求当前应用是双端（门户和移动端，传1）
		form.append('DoubleEnd', '1')
	}
	uploading.value = true


	try {
		const uuid = await grayscaleApi.importRoster(form)
		const impotSta = await grayscaleApi.getimport({ uuid })
		// 只有导入中是true
		if (impotSta) {
			const timer = setInterval(() => {
				grayscaleApi.getimport({ uuid }).then(r => {
					if (!r) {
						clearInterval(timer)
						searchFormState.current = 1
						searchFormState.size = 10
						loadData()
					}
				}).catch((err) => {
					if (timer) clearInterval(timer)
				})
			}, 1000);
		} else {
			searchFormState.current = 1
			searchFormState.size = 10
			loadData()
		}
		uploading.value = false
	} catch (error) {
		uploading.value = false
	}


}
// 下载名单
const exportList = () => {
	if (data.dataSource.length == 0) {
		message.warning('数据不存在，无法下载')
		return
	}
	uploading.value = true
	grayscaleApi
		.exportList(params.value)
		.then((res) => {
			const blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' })
			const contentDisposition = res.headers['content-disposition']
			const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
			const $link = document.createElement('a')
			$link.href = URL.createObjectURL(blob)
			$link.download = decodeURIComponent(patt.exec(contentDisposition)[1])
			$link.click()
			document.body.appendChild($link)
			document.body.removeChild($link) // 下载完成移除元素
			window.URL.revokeObjectURL($link.href) // 释放掉blob对象
			uploading.value = false
		})
		.catch(() => {
			uploading.value = false
		})
}
</script>

<style lang="less" scoped>
.btns {
	color: var(--primary-color);
	border-color: var(--primary-color);
	margin-top: 24px;
}

.box-pagin {
	margin-top: 24px;
	text-align: right;
}
</style>
